package cn.jeeweb.web.modules.cable.controller;

import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.http.ResponseCode;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mvc.controller.BaseBeanController;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.oss.exception.FileNameLengthLimitExceededException;
import cn.jeeweb.common.oss.exception.InvalidExtensionException;
import cn.jeeweb.common.query.annotation.PageableDefaults;
import cn.jeeweb.common.query.data.PropertyPreFilterable;
import cn.jeeweb.common.utils.FastJsonUtils;
import cn.jeeweb.common.utils.FileUtils;
import cn.jeeweb.common.utils.MessageUtils;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.cable.entity.*;
import cn.jeeweb.web.modules.cable.service.*;
import cn.jeeweb.web.modules.oss.entity.Attachment;
import cn.jeeweb.web.utils.PageRequest;
import cn.xjzn.framework_Core.ModuleActionType;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * @description:系统电缆
 */

@RestController
@RequestMapping("/cable/sysCable")
@ViewPrefix("modules/SysConfig")
@Log(title = "sys_cable")
public class SysCableController extends BaseBeanController<SysCable> {

    @Autowired
    private ISysCableService sysCableService;

    @Autowired
    private ICableTypeService cableTypeService;

    @Autowired
    private IRobotBrandService robotBrandService;

    @Autowired
    private IControllerTypeService controllerTypeService;

    @Autowired
    private ICablePurchaseOrderService cablePurchaseOrderService;

    @Autowired
    private ICableDetailService cableDetailService;

    boolean processFormula = false;
    DataFormatter formatter = new DataFormatter();
    FormulaEvaluator evaluator = null;


    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "ajaxList", method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")
    @Log(logType = ModuleActionType.SELECT)
    public void ajaxList(PropertyPreFilterable propertyPreFilterable, HttpServletRequest request, HttpServletResponse response) throws IOException {
        EntityWrapper<SysCable> entityWrapper = new EntityWrapper<>(entityClass);
        String cableTypeId = request.getParameter("cableTypeId");
        String robotBrandId = request.getParameter("robotBrandId");
        String controllerTypeId = request.getParameter("controllerTypeId");
        String cableName = request.getParameter("cableName");
        if (!StringUtils.isEmpty(cableTypeId)) {
            entityWrapper.eq("cableTypeId", cableTypeId);
        }
        if (!StringUtils.isEmpty(robotBrandId)) {
            entityWrapper.eq("robotBrandId", robotBrandId);
        }
        if (!StringUtils.isEmpty(controllerTypeId)) {
            entityWrapper.eq("controllerTypeId", controllerTypeId);
        }
        if (!StringUtils.isEmpty(cableName)) {
            entityWrapper.eq("cableName", cableName);
        }
        Page pageBean = sysCableService.selectPage(PageRequest.getPage(), entityWrapper);

        if(pageBean != null && pageBean.getRecords() != null && pageBean.getRecords().size() > 0){
           List<SysCable> sysCables = pageBean.getRecords();
            for(SysCable cable : sysCables){
                if(StringUtils.isNotBlank(cable.getCableTypeId())){
                    EntityWrapper<CableType> cableTypeWrapper = new EntityWrapper<>(CableType.class);
                    CableType cableType = cableTypeService.selectOne(cableTypeWrapper);
                    if(cableType != null){
                        cable.setCableTypeName(cableType.getCableType());
                        cable.setCableTypeCode(cableType.getCode());
                    }
                }

                if(StringUtils.isNotBlank(cable.getRobotBrandId())){
                    EntityWrapper<RobotBrand> robotBrandWrapper = new EntityWrapper<>(RobotBrand.class);
                    RobotBrand robotBrand = robotBrandService.selectOne(robotBrandWrapper);
                    if(robotBrand != null){
                        cable.setRobotBrandName(robotBrand.getBrandName());
                        cable.setRobotBrandCode(robotBrand.getCode());
                    }
                }

                if(StringUtils.isNotBlank(cable.getControllerTypeId())){
                    EntityWrapper<ControllerType> controllerTypeWrapper = new EntityWrapper<>(ControllerType.class);
                    ControllerType controllerType = controllerTypeService.selectOne(controllerTypeWrapper);
                    if(controllerType != null){
                        cable.setControllerTypeName(controllerType.getControllerTypeName());
                        cable.setControllerTypeCode(controllerType.getCode());
                    }
                }
            }
        }
        FastJsonUtils.print(pageBean);
    }

    @PostMapping("add")
    @Log(logType = ModuleActionType.INSERT)
    public Response add(SysCable entity, BindingResult result,
                        HttpServletRequest request, HttpServletResponse response) {
        // 验证错误
        this.checkError(entity, result);
        EntityWrapper<SysCable> entityWrapper = new EntityWrapper<>(SysCable.class);
        entityWrapper.eq("cableName", entity.getCableName());
        SysCable old = sysCableService.selectOne(entityWrapper);
        if (old != null) {
            return Response.error("保存失败，电缆名称已存在");
        } else {
            sysCableService.insert(entity);
            return Response.ok("添加成功");
        }
    }


    @PostMapping("{id}/update")
    @Log(logType = ModuleActionType.UPDATE)
    public Response update(SysCable entity, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        // 验证错误
        this.checkError(entity, result);
        EntityWrapper<SysCable> entityWrapper = new EntityWrapper<>(SysCable.class);
        entityWrapper.eq("cableName", entity.getCableName());
        SysCable old = sysCableService.selectOne(entityWrapper);
        if (old != null && !old.getId().equals(entity.getId())) {
            return Response.error("保存失败，电缆名称已存在");
        } else {
            sysCableService.insertOrUpdate(entity);
            return Response.ok("更新成功");
        }
    }

    @PostMapping("{id}/delete")
    @Log(logType = ModuleActionType.DELETE)
    public Response delete(@PathVariable("id") String id) {
        sysCableService.deleteById(id);
        return Response.ok("删除成功");
    }

    @PostMapping("batch/delete")
    @Log(logType = ModuleActionType.DELETE)
    public Response batchDelete(@RequestParam("ids") String[] ids) {
        List<String> idList = java.util.Arrays.asList(ids);
        sysCableService.deleteBatchIds(idList);
        return Response.ok("删除成功");
    }

    @RequestMapping(value = "getSysCableList", method = {RequestMethod.GET, RequestMethod.POST})
    @Log(logType = ModuleActionType.SELECT)
    public void getSysCableList() {
        EntityWrapper<SysCable> entityWrapper = new EntityWrapper<>(SysCable.class);
        List<SysCable> sysCables = sysCableService.selectList(entityWrapper);
        FastJsonUtils.print(sysCables);
    }

    @RequestMapping(value = "uploadSysCable", method = {RequestMethod.POST, RequestMethod.GET})
    public Response upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        Response responseResult = new Response();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getServletContext());
        List<SysCable> list = new ArrayList<SysCable>();
        if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> ite = multiRequest.getFileNames();
            while (ite.hasNext()) {
                MultipartFile file = multiRequest.getFile(ite.next());
                Workbook wb = null;
                try {
                    File file_ = new File(file.getOriginalFilename());
                    FileUtils.copyInputStreamToFile(file.getInputStream(), file_);
                    wb = WorkbookFactory.create(file_);
                    evaluator = wb.getCreationHelper().createFormulaEvaluator();
                    Sheet sheet0 = wb.getSheetAt(0);
                    int i = 0;
                    for (Row row : sheet0) {
                        if (row.getRowNum() < 1) {
                            //忽略表格的标题行
                            continue;
                        }

                        SysCable sysCable = new SysCable();
                        sysCable.setCableTypeName(getString(row, 0));
                        sysCable.setCableTypeCode(getString(row, 1));
                        sysCable.setRobotBrandName(getString(row, 2));
                        sysCable.setRobotBrandCode(getString(row, 3));
                        sysCable.setControllerTypeName(getString(row, 4));
                        sysCable.setControllerTypeCode(getString(row, 5));
                        sysCable.setVersion(getString(row, 6));
                        sysCable.setCableName(getString(row, 7));
                        sysCable.setCode(getString(row, 8));
                        sysCable.setPictureCode(getString(row, 9));
                        String length = getString(row, 11);
                        if (StringUtils.isBlank(length)) {
                            length = "0";
                        }
                        sysCable.setLength(Double.parseDouble(length));
                        if (StringUtils.isNotBlank(sysCable.getCableTypeName()) && StringUtils.isNotBlank(sysCable.getRobotBrandName()) && StringUtils.isNotBlank(sysCable.getControllerTypeName()) && StringUtils.isNotBlank(sysCable.getCableName()) && StringUtils.isNotBlank(sysCable.getVersion())) {
                            EntityWrapper<CableType> cableTypeWrapper = new EntityWrapper<>(CableType.class);
                            cableTypeWrapper.eq("cableType", sysCable.getCableTypeName());
                            cableTypeWrapper.eq("code", sysCable.getCableTypeCode());
                            CableType cableType = cableTypeService.selectOne(cableTypeWrapper);
                            if (cableType != null) {
                                sysCable.setCableTypeId(cableType.getId());
                            }

                            EntityWrapper<RobotBrand> robotBrandWrapper = new EntityWrapper<>(RobotBrand.class);
                            robotBrandWrapper.eq("brandName", sysCable.getRobotBrandName());
                            robotBrandWrapper.eq("code", sysCable.getRobotBrandCode());
                            RobotBrand robotBrand = robotBrandService.selectOne(robotBrandWrapper);
                            if (robotBrand != null) {
                                sysCable.setRobotBrandId(robotBrand.getId());
                            }

                            EntityWrapper<ControllerType> controllerTypeWrapper = new EntityWrapper<>(ControllerType.class);
                            controllerTypeWrapper.eq("controllerTypeName", sysCable.getControllerTypeName());
                            controllerTypeWrapper.eq("code", sysCable.getControllerTypeCode());
                            ControllerType controllerType = controllerTypeService.selectOne(controllerTypeWrapper);
                            if (controllerType != null) {
                                sysCable.setControllerTypeId(controllerType.getId());
                            }
                            list.add(sysCable);
                        }
                        i++;
                        System.out.println(i);
                    }
                    wb.close();
                    wb = null;
                } catch (InvalidFormatException e) {

                } finally {
                    if (wb != null) {
                        wb.close();
                    }
                }
            }
        }
        if (list.size() > 0) {
            for (SysCable cable : list) {
                sysCableService.insert(cable);
            }
        }
        return responseResult;
    }

    @RequestMapping(value = "uploadCablePurchaseOrder", method = {RequestMethod.POST, RequestMethod.GET})
    public Response uploadCablePurchaseOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        Response responseResult = new Response();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getServletContext());
        List<CablePurchaseOrder> cablePurchaseOrders = new ArrayList<CablePurchaseOrder>();
        if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> ite = multiRequest.getFileNames();
            while (ite.hasNext()) {
                MultipartFile file = multiRequest.getFile(ite.next());
                Workbook wb = null;
                try {
                    File file_ = new File(file.getOriginalFilename());
                    FileUtils.copyInputStreamToFile(file.getInputStream(), file_);
                    wb = WorkbookFactory.create(file_);
                    evaluator = wb.getCreationHelper().createFormulaEvaluator();
                    Sheet sheet0 = wb.getSheetAt(2);
                    for (Row row : sheet0) {
                        if (row.getRowNum() < 1) {
                            //忽略表格的标题行
                            continue;
                        }

                        CablePurchaseOrder cablePurchaseOrder = new CablePurchaseOrder();
                        cablePurchaseOrder.setCablePictureCode(getString(row, 0));
                        cablePurchaseOrder.setCodeRuleExplain(getString(row, 1));
                        cablePurchaseOrder.setPictureMaterielExplain(getString(row, 2));
                        cablePurchaseOrder.setBeforePosition(getString(row, 3));
                        cablePurchaseOrder.setBeforeConnector(getString(row, 4));
                        cablePurchaseOrder.setBeforeSex(getString(row, 5));
                        cablePurchaseOrder.setBeforeModel(getString(row, 6));
                        cablePurchaseOrder.setBeforeConnectorOrderNumbe(getString(row, 7));
                        cablePurchaseOrder.setBeforeNote(getString(row, 8));
                        cablePurchaseOrder.setAfterPosition(getString(row, 9));
                        cablePurchaseOrder.setBeforeConnector(getString(row, 10));
                        cablePurchaseOrder.setAfterSex(getString(row, 11));
                        cablePurchaseOrder.setAfterModel(getString(row, 12));
                        cablePurchaseOrder.setAfterConnectorOrderNumbe(getString(row, 13));
                        cablePurchaseOrder.setAfterNote(getString(row, 14));
                        cablePurchaseOrders.add(cablePurchaseOrder);
                    }
                    wb.close();
                    wb = null;
                } catch (InvalidFormatException e) {

                } finally {
                    if (wb != null) {
                        wb.close();
                    }
                }

            }


        }
        if (cablePurchaseOrders.size() > 0) {
            for (CablePurchaseOrder cablePurchaseOrder : cablePurchaseOrders) {
                cablePurchaseOrderService.insert(cablePurchaseOrder);
            }
        }
        return responseResult;
    }

    @RequestMapping(value = "uploadCableDetail", method = {RequestMethod.POST, RequestMethod.GET})
    public Response uploadCableDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        Response responseResult = new Response();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getServletContext());
        List<CableDetail> cableDetails = new ArrayList<CableDetail>();
        if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> ite = multiRequest.getFileNames();
            while (ite.hasNext()) {
                MultipartFile file = multiRequest.getFile(ite.next());
                Workbook wb = null;
                try {
                    File file_ = new File(file.getOriginalFilename());
                    FileUtils.copyInputStreamToFile(file.getInputStream(), file_);
                    wb = WorkbookFactory.create(file_);
                    evaluator = wb.getCreationHelper().createFormulaEvaluator();
                    Sheet sheet0 = wb.getSheetAt(3);
                    for (Row row : sheet0) {
                        if (row.getRowNum() < 1) {
                            //忽略表格的标题行
                            continue;
                        }

                        CableDetail cableDetail = new CableDetail();
                        cableDetail.setCableDetail(getString(row, 0));
                        cableDetail.setCableBrand(getString(row, 1));
                        cableDetail.setCableModel(getString(row, 2));
                        cableDetail.setCableDiameter(getString(row, 3));
                        cableDetails.add(cableDetail);
                    }
                    wb.close();
                    wb = null;
                } catch (InvalidFormatException e) {

                } finally {
                    if (wb != null) {
                        wb.close();
                    }
                }

            }
        }
        if (cableDetails.size() > 0) {
            for (CableDetail cableDetail : cableDetails) {
                cableDetailService.insert(cableDetail);
            }
        }
        return responseResult;
    }


    private String getString(Row row, int cellIndex) {

        Cell cell = row.getCell(cellIndex);
        if (cell == null) {
            return null;
        }
        int cellType = cell.getCellType();
        if (CellType.BLANK.equals(cellType)) {
            return null;
        }
        if (CellType.FORMULA.equals(cellType)) {
            if (!processFormula) {
                return null;
            }
            CellValue cellValue = evaluator.evaluate(cell);
            int cellType1 = cellValue.getCellType();
            if (CellType.STRING.equals(cellType1)) {
                return cellValue.getStringValue();
            } else if (CellType.ERROR.equals(cellType1)) {
                return null;
            } else if (CellType.BLANK.equals(cellType1)) {
                return null;
            } else {
                return cellValue.formatAsString();
            }
        }
        String text = formatter.formatCellValue(cell);
        if (text != null) {
            text = text.trim();
        }
        return text;
    }

}